package cn.hh.wechatkit.api.card;

import cn.hh.wechatkit.data.postdata.card.Meta_CardCheckTicketStatePostData;
import cn.hh.wechatkit.data.returndata.card.Meta_RData_CardState;
import cn.hh.wechatkit.exception.Wx_Exception_BadNetwork;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hhchat.kit.http.httpUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import static cn.hh.wechatkit.helper.WxConst.CheckTicketState_Post_URL;


/**
 * Created this one by HMH on 2017/5/7.
 * 查询code接口
 */
@Slf4j
public class WxAPI_Card_Check_Api {

    //日志
    private final static Logger logger = LoggerFactory.getLogger(WxAPI_Card_Check_Api.class);

    /**
     * 微信卡券状态查询 API
     * @param cardId 卡券Id
     * @param code 卡券code
     * @param ACCESS_TOKEN 基础Token
     * @return 卡券状态消息
     */
    public static Meta_RData_CardState check(String cardId, String code, String ACCESS_TOKEN)  {
        String url = CheckTicketState_Post_URL.replace("ACCESS_TOKEN", ACCESS_TOKEN);
        Meta_CardCheckTicketStatePostData postData = new Meta_CardCheckTicketStatePostData();
        postData.setCard_id(cardId);
        postData.setCode(code);
        Response response = null;
        try {
            response = httpUtil.postJson(url, postData);
        } catch (IOException e) {
            log.error(" ==> 网络请求失败", e);
            throw new Wx_Exception_BadNetwork("网络请求失败", e);
        }
        //获取数据
        if (response != null) {
            String body;
            try {
                body = response.body().string();
                return JSON.parseObject(body, Meta_RData_CardState.class);
            } catch (IOException e) {
                log.error(" ==> json转换失败", e);
                throw new Wx_Exception_InvalidJsonParse("json转换失败");
            }
        }
        throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错");
    }
}
